# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 10:29:21 2024

@author: 刘翼
"""

import cv2 
import numpy as np
img = cv2.imread(r"C:\Users\Public\opencv\Figure\digital0_9.png", 0) # 载入原图
image1 = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
# 二值化图像
ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 搜索轮廓
contours, hierarchy = cv2.findContours(thresh, 3, 2)
hierarchy = np.squeeze(hierarchy)
# 载入标准模板图
img_a = cv2.imread(r"C:\Users\Public\opencv\Figure\digital5.png", 0)
ret1, th = cv2.threshold(img_a, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours1, hierarchy1 = cv2.findContours(th, 3, 2)
template_a = contours1[0]  # 数字5的轮廓
# 记录最匹配的值的大小和位置
min_pos = 0
min_value = 9
for i in range(len(contours)):
    value = cv2.matchShapes(template_a,contours[i],1,0.0)
    if value < min_value:
        min_value = value
        min_pos = i
#绘制本条轮廓contours[min_pos]
cv2.drawContours(image1,[contours[min_pos]],0,[ 0,0,255],2)
cv2.imshow('result',image1)
cv2.waitKey(0)
cv2.destroyAllWindows()
